const path = require('path');
const express = require('express');
const cors = require('cors'); // 引入 cors 中间件
const articleRoutes = require('./routes/articleRoutes');
const imageRoutes = require('./routes/imageRoutes');
const lowcodeRoutes = require('./routes/lowcodeRoutes');

require('dotenv').config();

const app = express();

// 配置多个允许跨域的端口
const allowedOrigins = [
  'http://localhost:80',
  'http://localhost:3000', // 示例端口，可按需添加更多
  'http://localhost',
  undefined
];

const corsOptions = {
  // origin: function (origin, callback) {
  //   console.log('origin:', origin);
  //   if (allowedOrigins.includes(origin) || !origin) {
  //     // 允许请求，!origin 用于处理同源请求或没有 origin 头的情况
  //     callback(null, true);
  //   } else {
  //     // 拒绝请求
  //     callback(new Error('Not allowed by CORS'));
  //   }
  // },
  origin: '*',
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  preflightContinue: false,
  optionsSuccessStatus: 204
};

app.use(cors(corsOptions));

// 启用 JSON 请求体解析
app.use(express.json());

app.use('/api', lowcodeRoutes); // lowcode 路由
app.use('/api', articleRoutes); // 文章 路由
app.use('/api', imageRoutes); // 图片 路由
app.use('/uploads', express.static(path.join(__dirname, 'uploads'))); // 静态文件路由

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});